package smashedapples.google.googleapi
{
	import flash.display.DisplayObject;
	import flash.utils.Dictionary;
	
	import mx.core.Application;
	import mx.events.FlexEvent;
	
	import smashedapples.core.NonVisualComponent;
	import smashedapples.events.AsyncChainEvent;
	import smashedapples.events.AsyncEventChainResponder;
	import smashedapples.events.IAsyncChainResponder;
	import smashedapples.google.accounts.GoogleAuthResponse;
	import smashedapples.google.events.GoogleDataServiceEvent;
	import smashedapples.google.views.GoogleLoginTitleWindow;
	
	
	
	
	[DefaultProperty("services")]
	public class GoogleDataServices extends NonVisualComponent implements IAsyncChainResponder
	{	
		
		public var email:String;
		
		public var password:String;
		
		public var source:String;  
		
		[Inspectable(enumeration="true,false",defaultValue="true")]
		public var autoAuthenticate:Boolean = true;
		
		public function GoogleDataServices():void
		{
			this.addEventListener( FlexEvent.CREATION_COMPLETE, handleCreationComplete );
		}
		
		private function handleCreationComplete( event:FlexEvent ):void
		{
			if( email == null && autoAuthenticate == true )
				this.showAuthenticationForm();
		}
		
		
		public function showAuthenticationForm():void
		{
			GoogleLoginTitleWindow.show( this );
		}
		
		
		public function authenticate( email:String = null, password:String = null, responders:Array = null ):void
		{	
		
			this.setValueIfNotNull( "email", email )
			this.setValueIfNotNull( "password", password );
		
			var tokens:Array = [];
			
			for each( var service:IGoogleDataApi in this.services )
			{
				tokens.push( service.authenticate( this.email, this.password, this.source ) );
			}
			
			
			var chain:AsyncEventChainResponder = new AsyncEventChainResponder( tokens, responders );
		}
		
		
		public function handleAsyncChainComplete( event:AsyncChainEvent ):void
		{
			if( event.success )
				this.dispatchEvent( new GoogleDataServiceEvent( GoogleDataServiceEvent.AUTHENTICATED, this ) );
		}
		
		private function handleResult( response:GoogleAuthResponse ):void
		{
			trace("GoogleAuthResponse") ;
		}
		
		[ArrayElementType("smashedapples.google.googleapi.IGoogleDataApi")]
		public var services:Array = [];
				

		public var keys:Dictionary = new Dictionary();
		
		

	}
}


